package com.lx.util;

import io.minio.GetObjectArgs;
import io.minio.GetObjectResponse;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import jakarta.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * 封装文件上传下载组件
 */
@Component
public class MinIoUtil {
    @Resource
    private MinioClient minioClient;

    //绑定存储桶的名称
    @Value("${minio.bucketName}")
    private String bucketName;

    //文件上传组件
    public void upload(MultipartFile file) throws Exception {
        if (file.isEmpty()) {
            throw new Exception();
        }
        InputStream inputStream = file.getInputStream();
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(file.getOriginalFilename())
                //自动指定文件上传的类型
                .contentType(file.getContentType())
                .stream(inputStream, file.getSize(), -1).build());
    }

    //文件下载组件
    public InputStream downloadFile(String filename) throws Exception {
        if (filename.isEmpty()){
            throw new Exception();
        }
        GetObjectResponse fileObject = minioClient.getObject(GetObjectArgs.builder()
                .bucket(bucketName)
                .object(filename).build());
        return fileObject;

    }

}
